<?php
class LoginController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$form = new Application_Form_Login();
		$form->submit->setLabel('Login');
		$this->view->form = $form;
		
		if($this->getRequest()->isPost())
		{
			$formData = $this->getRequest()->getPost();
			 
			if ($form->isValid($formData))
			{
				$mytoken = Application_Helper_Session::get('token', '');
				$token = $form->getValue('token');
				
				if($token == $mytoken)
				{
					Application_Helper_Session::remove('token');
					
					$username = $form->getValue('username');
					
					$password = $form->getValue('password');
					$password = md5($password);
					
					$users = new Application_Model_DbTable_User();
					$userid = $users->authenticate($username, $password);
					
					if($userid)
					{
						Application_Helper_Session::set('uid', $userid);
						
						$this->redirect('/index');
					}
					else
					{
						$form->populate($formData);
					}
				}
				else
				{
					$form->populate($formData);
				}
			}
			else
			{
				$form->populate($formData);
			}
		}
		else 
		{
			$values = array();
			
			$token = time();
			Application_Helper_Session::set('token', $token);
			
			$values['token'] = $token;
			
			$form->populate($values);
		}
	}
	
	public function logoutAction()
	{
		Application_Helper_Session::remove('uid');
		
		$this->_helper->redirector('index');
	}
}